package club.hicode.daydayup.netty.udp.client2;

import club.hicode.daydayup.netty.udp.MessageBo;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramPacket;

import java.net.InetSocketAddress;

/**
 * 发送
 *
 * @author Liu Chunfu
 * @date 2018-07-09 下午8:10
 **/
public class Sendor {

    public SyncFuture<MessageBo> send(MessageBo message) {
        Channel channel = CommunicationContext.getChannel();
        //对方的ip地址
        InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 19876);
        //内容
        String content = JSONUtil.toJsonStr(message) + "$";
        ByteBuf bytebuf = Unpooled.copiedBuffer(content, CharsetUtil.CHARSET_UTF_8);

        //创建future对象并保存
        SyncFuture<MessageBo> future = new SyncFuture<>();
        CommunicationContext.addFuture(message.getId(), future);
        //发送
        DatagramPacket datagramPacket = new DatagramPacket(bytebuf, remoteAddress);
        System.out.println(DateUtil.now() + "发送了：" + content);
        channel.writeAndFlush(datagramPacket);
        return future;
        //return null;
    }
}
